package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ControllerAdvice 控制层功能增强注解
 * 对请求映射方法进行功能增强,在进入映射方法前或者在执行完映射方法后进行功能增强
 *
 * 这里我们使用的是执行完方法后进行功能增强
 */
@ControllerAdvice
public class CommonExceptionHandler {
    //异常处理注解(需要处理的异常类)
    @ExceptionHandler(LogicException.class)
    public void displayExp(Exception e, HttpServletResponse resp) throws IOException {
        e.printStackTrace();
        resp.setContentType("text/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSONString(new AjaxResult(false,e.getMessage())));
    }

    @ExceptionHandler(RuntimeException.class)
    public void runTimeExp(Exception e, HttpServletResponse resp) throws IOException {
        e.printStackTrace();
        resp.setContentType("text/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSONString(new AjaxResult(false,"系统出现未知异常,我们正在殴打程序员!")));
    }
}
